
//
//  DCIMChatListViewController.m
//  xmppBase
//
//  Created by striby on 16/1/7.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCIMChatListViewController.h"
#import "DCIMBaseTabBarViewController.h"
@interface DCIMChatListViewController ()
{
    NSIndexPath * selectedIndexPath;
    
    NSMutableDictionary * chatRooms;
}
@end

@implementation DCIMChatListViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (selectedIndexPath) {
        if (self.tableView) {
            [self.tableView reloadRowsAtIndexPaths:@[selectedIndexPath] withRowAnimation:UITableViewRowAnimationNone];
                DCIMBaseTabBarViewController * mainTab = (DCIMBaseTabBarViewController*)self.tabBarController;
            int unReadCount=0;
            for (XMPPMessageArchiving_Contact_CoreDataObject * contact in self.chatHistory) {
                unReadCount+=contact.unReadCount;
            }
            [mainTab setUnReadCout:unReadCount];
            
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    chatRooms = [[NSMutableDictionary alloc]initWithCapacity:1];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DCDeviceWidth, DCDeviceHeight)];
    self.tableView.delegate=self;
    self.tableView.dataSource =self;
    
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, TabBarHeight, 0)];
    
    [self.tableView setShowsVerticalScrollIndicator:NO];
    
    [self.view addSubview:self.tableView];
    
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self loadData];
//    [self noChatHistory];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:kXMPP_MESSAGE_CHANGE object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(roomConfigChanged:) name:kDidFetchConfigurationForm object:nil];
}


#pragma mark - load data
-(void)roomConfigChanged:(NSNotification*)noti
{
    XMPPRoom* room = noti.object;
    
    if ([[chatRooms allKeys]containsObject:room.roomJID.full]) {
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
           dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:@[[chatRooms objectForKey:room.roomJID.full]] withRowAnimation:UITableViewRowAnimationNone];
           });
        });
        
       
    }
}

-(void)loadData
{
    int unReadCount = 0;
    
    DCIMBaseTabBarViewController * mainTab = (DCIMBaseTabBarViewController*)self.tabBarController;
    
    
    
    XMPPMessageArchivingCoreDataStorage *storage = [DCXMPPTool shareInstance].xmppMessageArchivingCoreDataStorage;
    //查询的时候要给上下文
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:storage.contactEntityName inManagedObjectContext:storage.mainThreadManagedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"reciverID = %@", [DCXMPPTool shareInstance].xmppStream.myJID.full];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"mostRecentMessageTimestamp"
                                                                   ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [storage.mainThreadManagedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects != nil) {
        self.chatHistory = [[NSMutableArray alloc] initWithArray:fetchedObjects];
        //        [NSMutableArray arrayWithArray:fetchedObjects];
        if (self.chatHistory.count!=0) {
            [self clearNoChatHistory];
            
            for (XMPPMessageArchiving_Contact_CoreDataObject * contact in self.chatHistory) {
                unReadCount+=contact.unReadCount;
            }
            
            [mainTab setUnReadCout:unReadCount];
            
            
        }
        else
        {
            [self noChatHistory];
            [mainTab setUnReadCout:0];
        }
        
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        });
    }
    else
    {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self noChatHistory];
                [self.tableView reloadData];
                [mainTab setUnReadCout:0];
            });
        });
        
      
    }
    
  
}

-(void)clearNoChatHistory
{
    if ([self.view viewWithTag:333]) {
        [[self.view viewWithTag:333]removeFromSuperview];
    }
    self.tableView.hidden=NO;
}

-(void)noChatHistory
{
    if (![self.view viewWithTag:333]) {
        CGFloat width = 220;
        
        UIImageView * imageView =[[UIImageView alloc]initWithFrame:CGRectMake((DCDeviceWidth-width)/2, width, width, width/11.5*9.5)];
        imageView.image=[UIImage imageNamed:@"no_message_img"];
        imageView.tag = 333;
        [self.view addSubview:imageView];
        self.tableView.hidden=YES;

    }

}

#pragma mark - tableView delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMPPMessageArchiving_Contact_CoreDataObject * message = _chatHistory[indexPath.row];
    DCIMConversationViewController * vc = [[DCIMConversationViewController alloc]init];
    
    vc.targetJID = message.bareJid;
    
    vc.conversationType = DCConversationTypePrivate;
    
    vc.contactObj=message;
  
    
    
    //群聊
    if ([message.bareJid.domain hasPrefix:GroupDomainFirstName]) {
        vc.conversationType = DCConversationTypeGroup;
    }
    //单聊
    else
    {

        vc.conversationType = DCConversationTypePrivate;

    }
    
      [self.navigationController pushViewController:vc animated:YES];
    
    selectedIndexPath = indexPath;
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return chatListCellHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _chatHistory.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DCIMChatListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell = [[DCIMChatListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    
    XMPPMessageArchiving_Contact_CoreDataObject * message = _chatHistory[indexPath.row];
    
    
    
    XMPPvCardTemp * card = [[DCXMPPTool shareInstance].xmppvCardTempModule vCardTempForJID:message.bareJid shouldFetch:YES];
    
   
    
    // 是否群聊
    if ([message.bareJid.domain hasPrefix:GroupDomainFirstName]) {
//       XMPPRoom * room = [[XMPPRoom alloc]initWithRoomStorage:[DCIMGroupManager shareInstance] jid:message.bareJid];
//        cell.senderName.text = room.roomJID.user;
        cell.userIconImageView.image = [UIImage imageNamed:@"default_discussion_portrait"];
        
        XMPPJID * roomID = message.bareJid;
        
        
        [chatRooms setObject:indexPath forKey:roomID.full];
        
        NSString*  roomName = [[DCIMGroupManager shareInstance]getRoomNameWithRoomJid:roomID];
        
        if (roomName==nil) {
            cell.senderName.text = @"";
        }
        else
        {
            cell.senderName.text = roomName;
        }
        

    }
    else
    {
        cell.senderName.text = card.nickname;
        
        if (card.photo) {
            cell.userIconImageView.image=[UIImage  imageWithData:card.photo];
        }
        else
        {
            cell.userIconImageView.image = [UIImage imageNamed:@"defaultUserIcon"] ;
        }
    }
    
    
    
    cell.recentMessage.text = message.mostRecentMessageBody;

    
    NSDateFormatter * formatter =[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
  
    cell.recentTime.text =  [formatter stringFromDate: message.mostRecentMessageTimestamp];
    
    [cell setUnReadCount:message.unReadCount];
    return cell;
}



@end
